package com.haoxuer.discover.area.rest.resource;

import com.haoxuer.discover.area.api.apis.AreaApi;
import com.haoxuer.discover.area.api.domain.list.AreaList;
import com.haoxuer.discover.area.api.domain.page.AreaPage;
import com.haoxuer.discover.area.api.domain.request.*;
import com.haoxuer.discover.area.api.domain.response.AreaResponse;
import com.haoxuer.discover.area.api.domain.response.PoiResponse;
import com.haoxuer.discover.area.data.dao.AreaDao;
import com.haoxuer.discover.area.data.entity.Area;
import com.haoxuer.discover.area.rest.convert.AreaResponseConvert;
import com.haoxuer.discover.area.rest.convert.AreaSimpleConvert;
import com.haoxuer.discover.config.utils.ConverResourceUtils;
import com.haoxuer.discover.data.page.Filter;
import com.haoxuer.discover.data.page.Order;
import com.haoxuer.discover.data.page.Page;
import com.haoxuer.discover.data.page.Pageable;
import com.haoxuer.discover.data.utils.FilterUtils;
import com.haoxuer.lbs.qq.v1.builder.ServicesBuilder;
import com.haoxuer.lbs.qq.v1.domain.response.Geo;
import com.haoxuer.lbs.qq.v1.service.GeoCoderService;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.haoxuer.discover.user.rest.conver.PageableConver;
import com.haoxuer.discover.data.utils.BeanDataUtils;

import java.util.ArrayList;
import java.util.List;


@Transactional
@Component
public class AreaResource implements AreaApi {

    @Autowired
    private AreaDao dataDao;

    private String clearProvince(String province) {
        String result = "";
        if (province != null) {
            result = province.replace("省", "");
            result = result.replace("市", "");
            return result;
        }
        return result;
    }

    private String clearCity(String province) {
        String result = "";
        if (province != null) {
            result = province.replace("省", "");
            result = result.replace("市", "");
            result = result.replace("区", "");
            result = result.replace("县", "");
            if ("重庆".equals(result)) {
                return result + "城区";
            } else if ("北京".equals(result)) {
                return result + "城区";
            } else if ("上海".equals(result)) {
                return result + "城区";
            } else if ("天津".equals(result)) {
                return result + "城区";
            } else {
                return result;
            }

        }

        return result;
    }

    private String clearCounty(String province) {
        String result = "";
        if (province != null) {
            result = province.replace("省", "");
            result = result.replace("市", "");
            result = result.replace("区", "");
            result = result.replace("县", "");
            return result;
        }
        return result;
    }

    @Override
    public PoiResponse search(PoiSearchRequest request) {
        PoiResponse result = new PoiResponse();
        if (request.getAddress() == null) {
            result.setCode(501);
            result.setMsg("地址不存在");
            return result;
        }
        try {
            GeoCoderService service = ServicesBuilder.newBuilder().key("H4DBZ-WLVCU-YLEVF-4MIDF-MGB5H-TOFDR").build().geoGeoCoderService();

            Geo geo = service.address(request.getAddress());
            if (geo != null && geo.getLocation() != null) {
                result.setLat(Double.valueOf(geo.getLocation().getLat()));
                result.setLng(Double.valueOf(geo.getLocation().getLng()));
            }
            if (geo != null) {
                result.setAddress(geo.getTitle());
                result.setProvince(geo.getProvince());
                result.setCity(geo.getCity());
                result.setCounty(geo.getDistrict());
                Area area = dataDao.one(Filter.eq("name", clearProvince(geo.getProvince())));
                if (area != null) {
                    result.setProvinceId(area.getId());
                }
                Area city = dataDao.one(Filter.eq("name", clearCity(geo.getCity())), Filter.eq("levelInfo", 3));
                if (city != null) {
                    result.setCityId(city.getId());
                }
                Area county = null;
                if (city != null) {
                    county = dataDao.one(Filter.eq("parent.id", city.getId()),
                            Filter.eq("name", geo.getDistrict()));
                } else {
                    county = dataDao.one(Filter.eq("name", geo.getDistrict()));
                }
                if (county != null) {
                    result.setCountyId(county.getId());
                }
            }
        }catch (Exception e){
            result.setCode(500);
            result.setMsg(e.getMessage());
        }

        return result;
    }

    @Override
    public AreaResponse create(AreaDataRequest request) {
        AreaResponse result = new AreaResponse();

        Area bean = new Area();
        handleData(request, bean);
        dataDao.save(bean);
        result = new AreaResponseConvert().conver(bean);
        return result;
    }

    @Override
    public AreaResponse update(AreaDataRequest request) {
        AreaResponse result = new AreaResponse();
        if (request.getId() == null) {
            result.setCode(501);
            result.setMsg("无效id");
            return result;
        }
        Area bean = dataDao.findById(request.getId());
        if (bean == null) {
            result.setCode(502);
            result.setMsg("无效id");
            return result;
        }
        handleData(request, bean);
        result = new AreaResponseConvert().conver(bean);
        return result;
    }

    private void handleData(AreaDataRequest request, Area bean) {
        BeanDataUtils.copyProperties(request, bean);

    }

    @Override
    public AreaResponse delete(AreaDataRequest request) {
        AreaResponse result = new AreaResponse();
        if (request.getId() == null) {
            result.setCode(501);
            result.setMsg("无效id");
            return result;
        }
        dataDao.deleteById(request.getId());
        return result;
    }

    @Override
    public AreaResponse view(AreaDataRequest request) {
        AreaResponse result = new AreaResponse();
        Area bean = dataDao.findById(request.getId());
        if (bean == null) {
            result.setCode(1000);
            result.setMsg("无效id");
            return result;
        }
        result = new AreaResponseConvert().conver(bean);
        return result;
    }

    @Override
    public AreaList list(AreaSearchRequest request) {
        AreaList result = new AreaList();

        List<Filter> filters = new ArrayList<>();
        filters.addAll(FilterUtils.getFilters(request));
        List<Order> orders = new ArrayList<>();
        if ("asc".equals(request.getSortMethod())) {
            orders.add(Order.asc("" + request.getSortField()));
        } else if ("desc".equals(request.getSortMethod())) {
            orders.add(Order.desc("" + request.getSortField()));
        } else {
            orders.add(Order.desc("id"));
        }
        List<Area> organizations = dataDao.list(0, request.getSize(), filters, orders);
        AreaSimpleConvert convert = new AreaSimpleConvert();
        convert.setFetch(request.getFetch());
        ConverResourceUtils.converList(result, organizations, convert);
        return result;
    }

    @Override
    public AreaPage search(AreaSearchRequest request) {
        AreaPage result = new AreaPage();
        Pageable pageable = new PageableConver().conver(request);
        pageable.getFilters().addAll(FilterUtils.getFilters(request));
        if ("asc".equals(request.getSortMethod())) {
            pageable.getOrders().add(Order.asc("" + request.getSortField()));
        } else if ("desc".equals(request.getSortMethod())) {
            pageable.getOrders().add(Order.desc("" + request.getSortField()));
        } else {
            pageable.getOrders().add(Order.desc("id"));
        }
        Page<Area> page = dataDao.page(pageable);
        AreaSimpleConvert convert = new AreaSimpleConvert();
        convert.setFetch(request.getFetch());
        ConverResourceUtils.converPage(result, page, convert);
        return result;
    }
}
